package com.zll.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 1.获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        // 2.判断请求路径是否以login/register结尾，包含就不执行登录业务校验，所以返回false
        if (requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        // 3.如果不包含那么说明用户访问的资源是受保护的资源，那么需要执行登录校验
        return true;
    }


    @Override
    @SneakyThrows
    public Object run() throws ZuulException {
        // 1.获取到请求的token
        RequestContext requestContext = RequestContext.getCurrentContext();
        String token = requestContext.getRequest().getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        // 2.判断token是否存在
        if (StringUtils.isEmpty(token)) {
            try {
                // 如果用户没有登录，那么我们响应success、obj、message
                PrintWriter writer = response.getWriter();
                Map<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","请登录！");
                map.put("obj","noLogin");
                String jsonString = JSONObject.toJSONString(map);
                writer.write(jsonString);
                // 3.阻止过滤器后续执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 返回什么都可以，他会忽略
        return null;

    }
}
